package com.zqj.project.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqj.project.common.database.mybatis.conditions.Wraps;
import com.zqj.project.common.exception.BizException;
import com.zqj.project.converter.ReviewConverter;
import com.zqj.project.entity.ReviewPO;
import com.zqj.project.factory.ReviewFactory;
import com.zqj.project.model.Review;
import com.zqj.project.repository.ReviewMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Description: ReviewServiceImpl
 * @Author: 22001010704 Zhang Qijian
 * @CreateTime: 2024/11/8 15:39
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ReviewServiceImpl implements ReviewService {

    private final ReviewMapper reviewMapper;

    @Override
    public IPage<Review> page(Review review, IPage<Review> page) {
        final Long count = this.reviewMapper.selectCount(ReviewFactory.lbqWrapper(review));
        if (Objects.equals(0L, count)) {
            return page;
        }
        page.setTotal(count);
        return page.setRecords(ReviewConverter.toReviewModelList(this.reviewMapper.selectPage(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), ReviewFactory.lbqWrapper(review)).getRecords()));
    }

    @Override
    public Review info(Long orderId) {
        ReviewPO reviewPo = this.reviewMapper.selectOne(Wraps.<ReviewPO>lbQ().eq(ReviewPO::getOrderId, orderId));
        if (Objects.isNull(reviewPo)) {
            throw new BizException("评价不存在");
        }
        return ReviewConverter.toReviewModel(reviewPo);
    }

    @Override
    public List<Review> list(List<Long> orderIdList) {
        return ReviewConverter.toReviewModelList(this.reviewMapper.selectList(Wraps.<ReviewPO>lbQ().in(ReviewPO::getOrderId, orderIdList)));
    }

    @Override
    public List<Review> list(Long orderId) {
        return ReviewConverter.toReviewModelList(this.reviewMapper.selectList(Wraps.<ReviewPO>lbQ().eq(ReviewPO::getOrderId, orderId)));
    }

    @Override
    public Boolean add(Review review) {
        if (this.reviewMapper.selectCount(Wraps.<ReviewPO>lbQ().eq(ReviewPO::getOrderId, review.getOrderId())) > 0) {
            throw new BizException("该订单已评价");
        }
        return this.reviewMapper.insert(ReviewConverter.toReviewPo(review)) == 1;
    }

    @Override
    public Boolean edit(Review review) {
        return this.reviewMapper.updateById(ReviewConverter.toReviewPo(review)) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        return this.reviewMapper.deleteById(id) == 1;
    }

}